package com.java1234.controller;

import com.java1234.entity.Group;
import com.java1234.entity.MemberShip;
import com.java1234.entity.User;
import com.java1234.service.MemberShipService;
import com.java1234.util.ResponseUtil;
import com.java1234.util.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * Created by dengwubo on 2017/8/23.
 */
@Controller
@RequestMapping("/memberShip")
public class MemberShipController {

    @Resource
    private MemberShipService memberShipService;

    @RequestMapping("/update")
    public String update(String userId, String groupIds, HttpServletResponse response) throws Exception{
        memberShipService.deleteAllGroupByUserId(userId);
        if (StringUtil.isNotEmpty(groupIds)){
            String idsArr[] = groupIds.split(",");
            List<String> list = Arrays.asList(idsArr);
            list.forEach(id->{
                User user = new User();
                user.setId(userId);
                Group group = new Group();
                group.setId(id);
                MemberShip memberShip = new MemberShip();
                memberShip.setUser(user);
                memberShip.setGroup(group);
                memberShipService.add(memberShip);
            });
        }
        JSONObject result = new JSONObject();
        result.put("success",true);
        ResponseUtil.write(response,result);
        return null;
    }


}
